/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

/*
// 开放的接口
import http from './interface'

http.config.baseUrl = "http://localhost:8080/api/"

http.request(url:'user/list',method:'GET').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list', {status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.post('user', {id:1, status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.put('user/1', {status: 2}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.delete('user/1').then((res)=>{
	console.log(JSON.stringify(res))
}) 

*/
// import {
// 	ApiUrl
// } from '../env.js';
import global from '@/utils/global'
import { hideLoading } from '@/utils/helper';
import mApi from "@/utils/mapi";
export default {
	requestTree:{},
	config: {
		// baseUrl: ApiUrl,
		// baseUrl: "https://unidemo.dcloud.net.cn/",
		header: {
			'Content-Type': 'application/json;charset=UTF-8',
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		data: {},
		method: "POST",
		dataType: "json",
		/* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		// console.log("interface:", options)
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
		//TODO 加密数据

		//TODO 数据签名
		/* 
		_token = {'token': getStorage(STOREKEY_LOGIN).token || 'undefined'},
		_sign = {'sign': sign(JSON.stringify(options.data))}
		options.header = Object.assign({}, options.header, _token,_sign) 
		*/

		return new Promise((resolve, reject) => {
			let _config = null

			options.complete = (response) => {
				let statusCode = response.statusCode
				console.log("interface:", _config)
				// console.log("response:", statusCode)
				response.config = _config
				// console.log("response:", response)
				// if (process.env.NODE_ENV === 'development') {
				// 	if (statusCode === 200) {
				// 		console.log("【" + _config.requestId + "】 结果：" + JSON.stringify(response.data))
				// 	}
				// }
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				// 统一的响应日志记录
				_reslog(response)
				if (statusCode === 200) { //成功
					resolve(response.data);
				} else {
					reject(response.data)
				}
			}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}

			// 统一的请求日志记录
			// _reqlog(_config)
			if (process.env.NODE_ENV === 'development') {
				// console.log("【" + _config.requestId + "】 地址：" + _config.url)
				if (_config.data) {
					// console.log("【" + _config.requestId + "】 参数：" + JSON.stringify(_config.data))
				}
			}
			console.log('_config',_config)
			// this.requestTree
			_config.abortName&&this.abortRequest(_config.abortName)
			// console.log('this.requestTree-getSearchResult',global.REQUEST_TREE)
			_config.abortName?global.REQUEST_TREE[_config.abortName] = uni.request(_config):uni.request(_config);
			
		});
	},
	abortRequest(name){
		console.log('[name1]',name,global.REQUEST_TREE[name])
		console.log('[name1-2]',name,global.REQUEST_TREE)
		if(Array.isArray(name)){
			name.forEach(cname=>{
				if(global.REQUEST_TREE[cname]){
					global.REQOUEST_Tab = cname
					global.REQUEST_TREE[cname].abort();
					// delete global.REQUEST_TREE[name];
					global.REQUEST_TREE[cname] = undefined;
					console.log('[cname2]',global.REQUEST_TREE,global.REQUEST_TREE[cname])
				}
			})
			
		}else
		if(global.REQUEST_TREE[name]){
			global.REQUEST_TREE[name].abort();
			global.REQOUEST_Tab = name
			// delete global.REQUEST_TREE[name];
			global.REQUEST_TREE[name] = undefined;
			console.log('[name2]',global.REQUEST_TREE,global.REQUEST_TREE[name])
		}
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}

/**
 * 请求接口日志记录
 */
function _reqlog(req) {
	if (process.env.NODE_ENV === 'development') {
		// console.log("【" + req.requestId + "】 地址：" + req.url)
		if (req.data) {
			// console.log("【" + req.requestId + "】 请求参数：" + JSON.stringify(req.data))
		}
	}
	//TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		// console.log("【" + res.config.requestId + "】 地址：" + res.config.url)
		if (res.config.data) {
			// console.log( 'res.config.requestId',res.config.data)
		}
	}
	console.log( 'res.config.requestId',res)
	if(res.errMsg.includes('timeout')){
		uni.showToast({
		    title: '请求超时，请稍后再试',
		    icon: 'none'
		})
	}
	if(_statusCode!=200){
		hideLoading()
	}
	//TODO 除了接口服务错误外，其他日志调接口异步写入日志数据库
	switch (_statusCode) {
		case 200:
			break;
		case 403:
			mApi.msg('网络繁忙，请稍后')
			console.error('没有权限访问此资源')
			break;
		case 405:
			mApi.msg('网络繁忙，请稍后.')
			console.error('请求方法不被支持，请尝试其他方式访问')
			break;		
		case 401:
			mApi.msg('网络繁忙，请稍后...')
			console.error('请求未经授权，需要验证身份')
			break;
		case 404:
			console.error('未找到资源!')
			mApi.msg('网络繁忙，请稍后再试。')
			break;
		case 500:
			mApi.msg('服务器繁忙，请稍后再试')
			break;	
		case 502:
			mApi.msg('服务器繁忙，请稍后再试!')
			break;
		case 504:
			mApi.msg('服务器响应超时，请稍后再试')
			break;	
		default:
			break;
	}
}
